package cn.sanshuilin.kst.system.provider.write.dao;

import cn.sanshuilin.kst.common.utils.Utility;
import cn.sanshuilin.kst.system.provider.bean.Favorite;
import cn.sanshuilin.kst.system.provider.core.CurrentInfo;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author greenlee
 * @version v1.0
 * @create 创建时间: 2017-11-30 17:07
 * Copyright 2017  by 三水林科技有限公司
 **/
@Repository
public class FavoriteReq extends AbstractJpaDao<FavoriteReq> implements Serializable {

    public List<Favorite> canFavorite(String strProductID) {
            String hql = " SELECT f FROM Favorite f WHERE f.ProductID= :ProductID AND f.PubMemberID= :MemberID ";
            Query query = entityManager.createNativeQuery(hql,Favorite.class);
            query.setParameter("ProductID", strProductID);
            query.setParameter("MemberID", CurrentInfo.getCurrentMember().getId());
           return query.getResultList();
    }

    public long getCurrentMemberFavoritesCount(String strProductID) {
        long count = 0;
            Query query = this.getCurrentMemberFavoritesQuery(" COUNT(*) ", strProductID);
            count = Utility.toSafeLong(query.getSingleResult());
        return count;
    }

    private Query getCurrentMemberFavoritesQuery(String strChange, String strProductID) {
        String hql = "SELECT " + strChange + " FROM Favorite f WHERE  f.ProductID =:ProductID ";
        hql += " AND f.PubMemberID=:PubMemberID ";
        Query query = entityManager.createNativeQuery(hql);
        query.setParameter("ProductID", strProductID);
        query.setParameter("PubMemberID", CurrentInfo.getCurrentMember().getId());
        return query;
    }
    public long getFavoritesByProductIDCount(String strProductID) {
        long count = 0;
            Query query = this.getFavoritesByProductIDQuery(" COUNT(*) ", strProductID);
            count = Utility.toSafeLong(query.getSingleResult());
        return count;
    }


    // 关注作品
    public List<Favorite> getFavoritesByProductID(String strProductID) {
        List<Favorite> list = new ArrayList<Favorite>();
            Query query = getFavoritesByProductIDQuery("f", strProductID);
            list = query.getResultList();

        return list;
    }

    private Query getFavoritesByProductIDQuery(String strChange, String strProductID) {
        String hql = "SELECT " + strChange + " FROM Favorite f WHERE  f.ProductID = :ProductID ";
        hql += " ORDER BY f.PubDate ";
        Query query = entityManager.createNativeQuery(hql,Favorite.class);
        query.setParameter("ProductID", strProductID);
        return query;
    }

}
